﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using StaticPlugin;
using System.Windows.Forms;

namespace MosWar
{
    class jMakePetrics : AJob
    {
        string status = "idle";
        string balansPetriks = "";
        jMakePetricsSetup setup = new jMakePetricsSetup();

        bool available
        {
            get
            {
                return Properties.Settings.Default.cbActivePetrics;
            }
        }
        int priority
        {
            get
            {
                return (int)Properties.Settings.Default.pNumPriorityPetrics;
            }
        }
        int minRudaToProcess
        {
            get
            {
                return (int)Properties.Settings.Default.pNumMinRudaToPetrics;
            }
        }
        int minBabloToProcess
        {
            get
            {
                return (int)Properties.Settings.Default.numMinBabloToPetrics;
            }
        }
        DateTime processPetricsTime
        {
            get
            {
                if (setup.tbProcessTime.Text == "") setup.tbProcessTime.Text = DateTime.Now.ToString();
                DateTime dt;
                if (DateTime.TryParse(Properties.Settings.Default.pTbProcessTimePetrics, out dt))
                {
                    return dt;
                }
                return DateTime.Now;
                //throw new Exception();
            }
            set
            {
                Properties.Settings.Default["pTbProcessTimePetrics"] = value.ToString();
                setup.tbProcessTime.Text = value.ToString();
                Properties.Settings.Default.Save();
            }
        }

        #region Interface to AJob

        public override DialogResult showSetupDialog()
        {
            return setup.ShowDialog();
        }

        protected override string getName()
        {
            return "Изготовление нано-петриков";
        }

        protected override string getStatus()
        {
            string s = "";
            if (balansPetriks != "") s = s + "Всего петриков: " + balansPetriks + ". ";
            if (processPetricsTime > DateTime.Now)
                s = s + "Делаем петрики до " + processPetricsTime.ToShortTimeString();
            s = s + status;
            return s;
        }

        protected override bool getAvailable()
        {
            return available;
        }

        protected override int getPriority()
        {
            return priority;
        }

        public override bool testRequirements(WebBrowser b)
        {
            if (b.Document == null)
            {
                return false;
            }
            if (b.Document.Body == null)
            {
                return false;
            }
            if (b.IsBusy)
            {
                return false;
            }
            int money = SkillsDetector.getMoney(b);
            int ruda = SkillsDetector.getRuda(b);

            if (money - 500 < minBabloToProcess) 
            {
                status = "Недостаточно денег! надо мин. " + (minBabloToProcess + 500).ToString();
                return false;
            }
            if (ruda - 5 < minRudaToProcess)
            {
                status = "Недостаточно руды! надо мин. " + (minRudaToProcess + 5).ToString();
                return false;
            }
            if (DateTime.Now < processPetricsTime)
            {
                status = "Ждем до " + processPetricsTime.ToShortTimeString();
                return false;
            }
            status = "...";
            return true;
        }

        public override void initActions()
        {
            status = "";
            actions.Clear();
            actions.Add(new Action("GotoZavod", GotoZavod));
            actions.Add(new Action("testPetrics", testPetrics));
        }
        #endregion

        #region Actions

        void GotoZavod(WebBrowser b)
        {
            status = "Идем на завод";
            if (b.Url.AbsolutePath != "/factory/") b.Navigate("www.moswar.ru/factory/");
        }

        void testPetrics(WebBrowser b)
        {
            HtmlElement frmPetrics = WebParserEx.getTagByClassName(b.Document.Body, "form", "factory-nanoptric");
            if (frmPetrics == null)
            {
                status = "Ошибка загрузки формы с петриками";
                Console.WriteLine(status);
                actions.Clear();
                return;
            }

            balansPetriks = WebParserEx.getTagByClassName(frmPetrics, "p", "total").GetElementsByTagName("span")[0].InnerText;
            Console.WriteLine("Получен баланс петриков: " + balansPetriks);
            HtmlElement btnStartPetrics = WebParserEx.getTagByClassName(frmPetrics, "button", "button");
            if (btnStartPetrics == null) // Не нашли кнопку для петриков. м.б. переработка уже идет?
            {
                Console.WriteLine("testPetrics:: Не нашли кнопку начала переработки петриков");
                HtmlElement timer = WebParserEx.getTagByClassName(frmPetrics, "td", "value");
                if (timer == null)
                {
                    throw new Exception("Непонятная ошибка!!");
                    //return;
                }
                TimeSpan ts = TimeSpan.FromSeconds(double.Parse(timer.GetAttribute("timer")));
                processPetricsTime = DateTime.Now + ts;
                if (ts == TimeSpan.Zero) b.Navigate("/player");
                //status = "Делаем петрики до " + processPetricsTime.ToShortTimeString();
                return;
            }
            // нажмем на кнопку
            btnStartPetrics.InvokeMember("click");
            actions.Add(new Action("Повторная заявка на testPetrics чтобы установить таймер", testPetrics));
            status = "...";// "Начинаем переработку";
        }

        #endregion
    }
}
